#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
        ListNode* L1 = headA;
        ListNode* L2 = headB;
        while (L1 && L2)
        {
            L1 = L1->next;
            L2 = L2->next;
        }
        while (L1 || L2)
        {
            if (L1)
            {
                L1 = L1->next;
                headA = headA->next;
            }
            else
            {
                L2 = L2->next;
                headB = headB->next;
            }
        }
        while (headA != headB)
        {
            headA = headA->next;
            headB = headB->next;
        }

        return headA;
    }
};